package com.ai.hear;

import com.ai.analysis.StoreHouse;
import com.base.SnThread;
import com.iflytek.cloud.speech.RecognizerListener;
import com.iflytek.cloud.speech.RecognizerResult;
import com.iflytek.cloud.speech.SpeechConstant;
import com.iflytek.cloud.speech.SpeechError;
import com.iflytek.cloud.speech.SpeechRecognizer;

/**
 * @Description 听写
 * @ClassName DictationOperator
 * @Date 2017年8月10日 下午2:46:34
 * @Author yanghao Copyright (c) All Rights Reserved, 2017.
 */
public class DictationOperator extends SnThread {

	private SpeechRecognizer mIat;

	public DictationOperator() {
		this.mIat = SpeechRecognizer.createRecognizer();
		this.mIat.setParameter(SpeechConstant.DOMAIN, "iat");
		this.mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
		this.mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
		this.mIat.startListening(mRecoListener);
	}

	// 听写监听器
	private RecognizerListener mRecoListener = new RecognizerListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			String text = results.getResultString();
			if (isLast) {
				goon();
			} else {
				System.out.println("dop = " + text);
				StoreHouse.addRaw(text);
			}
		}

		// 会话发生错误回调接口
		public void onError(SpeechError error) {
			// if (null != error) {
			// error.getErrorDescription(true); // 获取错误码描述
			// }
			goon();
		}

		// 开始录音
		public void onBeginOfSpeech() {
			// DebugLog.Log("开始");
		}

		// 音量值0~30
		public void onVolumeChanged(int volume) {
			// DebugLog.Log("onVolumeChanged");
			if (volume == 0)
				volume = 1;
			else if (volume >= 6)
				volume = 6;
		}

		// 结束录音
		public void onEndOfSpeech() {
			// DebugLog.Log("结束");
			// goon();
		}

		// 扩展用接口
		public void onEvent(int eventType, int arg1, int arg2, String msg) {
		}
	};

	private boolean goon = true;

	private void goon() {
		if (this.goon) {
			mIat.startListening(mRecoListener);
		} else {
			this.mIat.stopListening();
		}
	}

}
